# -*- coding: utf-8 -*-
"""
@Time    : 2021/4/13 9:23
@Author  : hui lin
"""
import os

import pygame
from pygame import Surface

from client.config import ClientConfig
from client.model.entity_base import EntityBase
from package.posi import Position
from package.static.const import MoveDirection, Faction, TypeIdConst
from package.universe import EsException, universe


class Bullet(EntityBase):

    def __init__(self, type_id: TypeIdConst, faction: Faction, position: Position, direction: MoveDirection, **kwargs):
        super().__init__(type_id, **kwargs)
        self._faction: Faction = faction

        # 缓存的行进距离
        self._cache_move: float = 0
        # 最小移动距离
        self.min_move: int = 4

        self.image: Surface = Surface((24, 24))
        self.hurt = universe.get_bullet_special_info(type_id).hurt

        self.set_direction(direction)
        self._init_position(position)

    def __str__(self):
        return "<{} rect={} direction={}>".format(self.__class__.__name__, self.rect, self.direction)

    __repr__ = __str__

    def set_direction(self, direction: MoveDirection):
        if MoveDirection.NONE == direction:
            raise EsException("BulletDirectionError")
        self.direction = direction

        root_dir = ClientConfig().root_dir
        image_path = os.path.join(root_dir, self.static_info.image[self._faction][direction-1])
        self.image.blit(pygame.image.load(image_path).convert_alpha(), (6, 6))
        self.rect = self.image.get_rect()

    def _init_position(self, position: Position):
        self.rect.center = position.x, position.y

    def get_hurt(self) -> int:
        """获取可以造成的最大伤害"""
        return self.hurt

    def get_anti_hurt(self) -> int:
        """撞击别人时自己受到的反伤"""
        return int(self.hurt / 10)

    def receive_anti_hurt(self):
        self.receive_hurt(self.get_anti_hurt())

    def _move(self, x: int, y: int):
        self.rect = self.rect.move(x, y)

    def try_move_cur(self, frame_physical_rate: int) -> int:
        """
        尝试往当前方向移动
        :param frame_physical_rate: 帧率
        :return: int, 0/1 是否发生了移动
        """
        # if frame_physical_rate % 5 != 0:
        #     return 0
        interval = 1.0 / frame_physical_rate
        real_speed = self.real_speed
        if 0.001 < real_speed and self.direction:
            if self.direction in [MoveDirection.UP, MoveDirection.LEFT]:
                new_move = -1.0 * interval * real_speed
            else:
                new_move = 1.0 * interval * real_speed
            max_move = self._cache_move + new_move
            # 移动距离 = （理论最大距离 // 最小格子数）* 格子像素
            real_move: int = int(max_move // self.min_move) * self.min_move
            self._cache_move = max_move - real_move

            if self.direction in [MoveDirection.UP, MoveDirection.DOWN]:
                self._move(0, real_move)
            else:
                self._move(real_move, 0)
            if real_move:
                return 1
        return 0
